package cn.tqfeiyang.smartadmin.commons.pagination;

import cn.tqfeiyang.smartadmin.commons.Constants;
import cn.tqfeiyang.smartadmin.commons.toolbox.FieldUtils;
import cn.tqfeiyang.smartadmin.commons.toolbox.StringUtils;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.annotation.JsonIgnore;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;

/**
 * 页面参数，包括页码和大小
 *
 * @author tqfeiyang
 * @since 2024/9/10 15:14
 */
@Data
public class PageParams {

    @Schema(description = "页码，默认为 1", example = "1")
    private Integer pageNum = Constants.PAGE_DEFAULT_INDEX;

    @Schema(description = "页大小，默认为 10", example = "10")
    private Integer pageSize = Constants.PAGE_DEFAULT_SIZE;

    public Integer getPageNum() {
        if (pageNum == null || pageNum <= 0) {
            pageNum = Constants.PAGE_DEFAULT_INDEX;
        }
        return pageNum;
    }

    public Integer getPageSize() {
        if (pageSize == null || pageSize <= 0) {
            pageSize = Constants.PAGE_DEFAULT_SIZE;
        }
        return pageSize;
    }

    /**
     * 获取排序条件，注意不包含 order by
     *
     * @return 返回排序条件，没有排序条件时返回null
     */
    public String getCustomOrderBySegment() {
        final String ORDER_BY_FIELD = "orderBy";
        final String ORDER_DIRECTION_FIELD = "direction";

        Object orderByValue = FieldUtils.getFieldValue(this, ORDER_BY_FIELD);
        if (orderByValue == null) {
            return null;
        } else {
            if (!(orderByValue.getClass().isEnum() || String.class.isAssignableFrom(orderByValue.getClass()))) {
                throw new RuntimeException("查询请求类" + getClass().getName() + "中的" + ORDER_BY_FIELD + "字段必须是枚举类型或字符串类型");
            }
        }

        Object directionValue = FieldUtils.getFieldValue(this, ORDER_DIRECTION_FIELD);
        if (directionValue == null) {
            directionValue = OrderDirection.asc;
        } else {
            if (!(OrderDirection.class.isAssignableFrom(directionValue.getClass()))) {
                throw new RuntimeException("查询请求类" + getClass().getName() + "中的" + ORDER_DIRECTION_FIELD + "字段必须是OrderDirection枚举类型");
            }
        }

        return StringUtils.camelToUnderline(orderByValue.toString()) + " " + directionValue.toString();
    }

}